package com.ansion.basedb.dao.model;

import android.text.TextUtils;
import android.util.Log;

import androidx.annotation.NonNull;

import com.ansion.basedb.dao.LoginedUserMgr;
import com.ansion.basedb.dao.UserFTSHelper;
import com.ansion.bean.GroupInfo;
import com.ansion.log.VLog;
import com.ansion.utils.ContactUtil;

import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.atomic.AtomicBoolean;

/**
 * Created by apple on 14-6-24.
 */
public class GroupModel extends BaseModel {
    public final static String kColumnName_Group_Id = "group_id";
    public final static String kColumnName_Group_Name = "group_name";
    public final static String kColumnName_Group_Avatar = "group_avatar";
    public final static String kColumnName_Members = "members";
    public final static String kColumnName_Voipids = "voipids";//存储json , uid 对应 voipid
    public final static String kColumnName_Silent = "isSilent";//是否静音
    public final static String kColumnName_Creator = "creator";
    public final static String kColumnName_Discription = "discription";//公告描述
    public static final String kColumnName_BackGround = "background";
    public static final String kColumnName_QrcodeUrl = "qrcodeurl"; //群组二维码地址
    public static final String kColumnName_GroupUpdateTime = "group_updatetime"; //群组更新时间
    public static final String kColumnName_GroupAdmin = "group_admin"; //群组更新时间
    public static final String kColumnName_GroupType = "group_type";
    public static final String kColumnName_GroupShareLink = "share_link"; //群主的link
    public static final String kColumnName_linkExpireTime = "linkExpireTime"; //link的过期时间
    public static final String KColumnName_CreateTime = "create_time"; //群创建时间
    public static final String KColumnName_UcidLoad = "ucid_load"; //ucid是否创建过
    public static final String kColumnName_lastRequestTime = "last_request_time"; //ucid是否创建过

    public static final int ISSILENT_TRUE = 1;
    public static final int ISSILENT_FALSE = 0;

    public static final int CHAT_GROUP = 0;
    public static final int VOIP_GROUP = 1;

    @DatabaseField(columnName = kColumnName_Group_Id, index = true, unique = true, canBeNull = false)
    private long id;

    @DatabaseField(columnName = kColumnName_Group_Name)
    private String groupName;

    @DatabaseField(columnName = kColumnName_Group_Avatar)
    private String groupAvatar;

    @DatabaseField(columnName = kColumnName_Members)
    private String groupMembers;

    @DatabaseField(columnName = kColumnName_Silent)
    private int isSilent;

    @DatabaseField(columnName = kColumnName_Creator)
    private long creator;

    @DatabaseField(columnName = kColumnName_Discription)
    private String discription;

    private int memberCount = -1; //群人数

    @DatabaseField(columnName = kColumnName_BackGround)
    private String background;

    @DatabaseField(columnName = kColumnName_QrcodeUrl)
    private String qrCodrUrl;

    @DatabaseField(columnName = kColumnName_GroupUpdateTime)
    private long groupUpdateTime;

    @DatabaseField(columnName = kColumnName_GroupAdmin)
    private String groupAdmin;

    @DatabaseField(columnName = kColumnName_Voipids)
    private String vopids;

    @DatabaseField(columnName = kColumnName_GroupType)
    private int groupType;

    @DatabaseField(columnName = kColumnName_GroupShareLink)
    private String shareLink;

    @DatabaseField(columnName = kColumnName_linkExpireTime)
    private long linkExpireTime;

    @DatabaseField(columnName = KColumnName_CreateTime)
    private long createTime;

    @DatabaseField(columnName = KColumnName_UcidLoad)
    private boolean ucidLoad = false;


    // 用于记录上次同步服务器的时间,单位 s
    @DatabaseField(columnName = kColumnName_lastRequestTime)
    private long lastRequestTime;


    private String displayName; //无群组名，显示成员名称

    private String groupCallName; //用于groupcall的显示

    private String originalAvatar;

    private HashMap<Long, Integer> cacheUIds = new HashMap<Long, Integer>();

    public static AtomicBoolean isNeedReCreate = new AtomicBoolean(false);

    //是否需要请求groupInfo，用于处理memberLeave时候新建空群导致无法触发请求groupInfo
    private boolean needRequestInfo = false;


//	private String groupAvatarOld;

    public GroupModel() {

    }

    public GroupModel(GroupInfo info) {

        this.id = info.getGid();
        this.groupName = info.getName();
        this.creator = info.getCreator();
        this.groupAvatar = info.getAvatar();
        this.isSilent = info.isSilent() ? 1 : 0;
        this.groupUpdateTime = info.getUpdate();
        this.groupAdmin = getAdminToString(info.getManager());
        this.groupType = info.getType();
        this.memberCount = info.getMemberCount();

    }

    public long getId() {
        return id;
    }

    public String getUid() {
        return String.valueOf(id);
    }

    public void setId(long id) {
        this.id = id;
    }

    public String getGroupName() {
        return groupName;
    }

    public void setGroupName(String groupName) {
        this.groupName = groupName;
    }

    public boolean isUcidLoad() {
        return ucidLoad;
    }

    public void setUcidLoad(boolean ucidLoad) {
        this.ucidLoad = ucidLoad;
    }

    public String getGroupAvatar() {
//		if (!TextUtils.isEmpty(groupAvatar)) {
//			String file = FileCacheStore.getCacheFilePathByUrl(groupAvatar);
//			if (TextUtils.isEmpty(file)) {
//				if (groupAvatar.startsWith("http")) {
//					DownLoadManager.download(groupAvatar);
//				}
//
//				if (!TextUtils.isEmpty(groupAvatarOld)) {
//					String oldFile = FileCacheStore.getCacheFilePathByUrl(groupAvatarOld);
//					if (!TextUtils.isEmpty(oldFile)) {
//						return groupAvatarOld;
//					}
//				}
//			}
//		}

        return groupAvatar;
    }

    public String getGroupOriginalAvatar() {
        return "";//ImageManager.getAvatarUrl(groupAvatar);
    }

    public void setGroupAvatar(String groupAvatar) {
        if (null != groupAvatar && groupAvatar.equals(this.groupAvatar)) {
            return;
        }

//		String file = FileCacheStore.getCacheFilePathByUrl(this.groupAvatar);
//		if (!TextUtils.isEmpty(file)) {
//			// groupAvatarOld赋值前先看看this.groupAvatar头像本地下载下来没有
//			groupAvatarOld = this.groupAvatar;
//		}
        this.groupAvatar = groupAvatar;

//		if (!TextUtils.isEmpty(groupAvatar) && groupAvatar.startsWith("http")) {
//			DownLoadManager.download(groupAvatar);
//		}
    }

    public String getGroupMembers() {
        return groupMembers;
    }

    @NonNull
    public List<String> getGroupMemberUidList() {
        return getGroupMemberUidList(groupMembers);
    }

    @NonNull
    public static List<String> getGroupMemberUidList(String groupMembers) {
        List<String> uidList = null;
        if (!TextUtils.isEmpty(groupMembers)) {
            try {
                JSONArray data = new JSONArray(groupMembers);
                if (data.length() > 0) {
                    uidList = new ArrayList<>(data.length());
                    for (int i = 0; i < data.length(); i++) {
                        JSONObject obj = data.optJSONObject(i);
                        if (obj != null) {
                            String uid = obj.optString("uid");
                            if (!TextUtils.isEmpty(uid)) {
                                uidList.add(uid);
                            }
                        }
                    }
                }
            } catch (Exception ignore) {

            }
        }
        if (uidList == null) {
            uidList = new ArrayList<>(0);
        }
        return uidList;
    }

    public void setGroupMembers(String groupMembers) {
        this.groupMembers = groupMembers;
        if (VLog.OPEN_LOG) {
            if (getUserIdSet().isEmpty()) {
                VLog.e("TAG_CONTACT", "try to setGroupMembers with empty:" + Log.getStackTraceString(new Throwable()));
            }
        }
    }

    public String getVopids() {
        return vopids;
    }

    public void setVopids(HashMap<Long, Integer> map) {

        if (map != null && !map.isEmpty()) {

            cacheUIds = map;
            JSONArray json = new JSONArray();
            Iterator<Map.Entry<Long, Integer>> it = map.entrySet().iterator();
            groupCallName = "";

            try {
                while (it.hasNext()) {
                    Map.Entry<Long, Integer> entry = it.next();
                    JSONObject o = new JSONObject();
                    o.put("uid", entry.getKey());
                    o.put("voipid", entry.getValue());
                    json.put(o);
                }
                vopids = json.toString();
                VLog.d("GroupModel", "voipids == " + vopids);
            } catch (Exception e) {
                VLog.d("GroupModel", "setVopids exception");
            }
        }
    }

    public int getVoipid(long uid) {
        if (cacheUIds != null && cacheUIds.size() == 0) {
            if (!TextUtils.isEmpty(vopids) && vopids.length() > 2) {

                try {
                    JSONArray data = new JSONArray(vopids);

                    for (int i = 0; i < data.length(); i++) {
                        JSONObject obj = data.getJSONObject(i);
                        if (obj == null) {
                            continue;
                        }
                        long userId = obj.optLong("uid");
                        int voipid = obj.optInt("voipid");
                        cacheUIds.put(userId, voipid);
                    }

                } catch (Exception e) {
                    VLog.d("GroupModel", "exception");
                }

            }
        }

        if (cacheUIds != null) {
            if (cacheUIds.containsKey(uid)) {
                return cacheUIds.get(uid);
            }
        }
        return ContactUtil.INVALID_ID;
    }

    public Long getUid(int voipid) {
        if (cacheUIds != null) {
            for (long key : cacheUIds.keySet()) {
                int value = cacheUIds.get(key);
                if (value == voipid) {
                    return key;
                }
            }
        }
        return -1L;
    }

//	public int getGroupType() {
//		return groupType;
//	}

    public void setGroupType(int groupType) {
        this.groupType = groupType;
    }

    public void setDisplayName(String displayName) {
        this.displayName = displayName;
        groupCallName = "";
    }

    public String getGroupCallName() {
        return groupCallName;
    }

    public void setGroupCallName(String groupCallName) {
        this.groupCallName = groupCallName;
    }

    /**
     * 请使用GroupModelNameUtils.getDisplayName来获取群名称。
     */
    @Deprecated
    public String getDisplayName() {
        return displayName;
    }

    public int getMemberCount() {

        if (memberCount != -1) {
            return memberCount;
        } else {
            return memberCount = getUserIdSet().size();
        }

    }

//	public void setMemberCount(int memberCount) {
//		this.memberCount = memberCount;
//	}

    public boolean isMeInGroup() {
        CurrentUser loginedUser = LoginedUserMgr.getCurrentLoginedUser();
        if (loginedUser == null) {
            return false;
        }

        if (!TextUtils.isEmpty(groupMembers) && groupMembers.length() > 2) {

            try {
                JSONArray data = new JSONArray(groupMembers);

                for (int i = 0; i < data.length(); i++) {
                    JSONObject obj = data.getJSONObject(i);
                    if (obj == null) {
                        continue;
                    }
                    long id = obj.optLong("uid", ContactUtil.INVALID_ID);
                    if (id == loginedUser.getUserId()) {
                        return true;
                    }
                }

            } catch (Exception e) {
                return false;
            }
        }
        return false;

    }

    public boolean isMember(@NonNull String uid) {
        if (!TextUtils.isEmpty(groupMembers)) {
            try {
                JSONArray data = new JSONArray(groupMembers);
                for (int i = 0; i < data.length(); i++) {
                    JSONObject obj = data.optJSONObject(i);
                    if (obj != null) {
                        String uidString = obj.optString("uid");
                        if (TextUtils.equals(uidString, uid)) {
                            return true;
                        }
                    }
                }
            } catch (Exception ignore) {

            }
        }
        return false;
    }

    /**
     * 获取除自己以外其他成员Id
     *
     * @return
     */
    public Set<Long> getOtherUserSet() {
        Set<Long> userIdSet = new LinkedHashSet<Long>();
        userIdSet = getUserIdSet();
        final CurrentUser loginedUser = LoginedUserMgr.getCurrentLoginedUser();
        if (null != loginedUser) {
            userIdSet.remove(loginedUser.getUserId());
        }

        return userIdSet;
    }

    public boolean getIsSilent() {
        return isSilent == ISSILENT_TRUE;
    }

    public void setIsSilent(int isSilent) {
        this.isSilent = isSilent;
    }

    public long getCreator() {
        return creator;
    }

    public void setCreator(long creator) {
        this.creator = creator;
    }


    public String getDiscription() {
        return discription;
    }

    public void setDiscription(String discription) {
        this.discription = discription;
    }

    /**
     * 设置群成员
     *
     * @param ids
     * @return
     */
    public String getSetToString(Set<Long> ids) {

        if (ids == null) {
            return "";
        }
        memberCount = ids.size();
        JSONArray json = new JSONArray();
        try {
            for (Long id : ids) {
                if (id == ContactUtil.INVALID_ID)
                    continue;
                JSONObject o = new JSONObject();
                o.put("uid", id);
                json.put(o);
            }
        } catch (Exception e) {
            VLog.d("GroupModel", "exception");
        }
        if (ids.isEmpty() || json.length() == 0) {
            VLog.e("TAG_CONTACT", "try to setGroupMembers with empty:" + Log.getStackTraceString(new Throwable()));
        }
        return json.toString();
    }

    /**
     * 将adminlist转成String
     *
     * @param adminList
     * @return
     */
    public String getAdminToString(List<Long> adminList) {

        if (adminList == null || adminList.size() == 0) {
            return "";
        }

        JSONArray json = new JSONArray();
        try {
            for (Long id : adminList) {
                if (id == ContactUtil.INVALID_ID)
                    continue;
                JSONObject o = new JSONObject();
                o.put("uid", id);
                json.put(o);
            }
        } catch (Exception e) {
            VLog.d("GroupModel", "exception");
        }
        return json.toString();
    }

    /**
     * 将groupadmin 转成list
     *
     * @return
     */
    public List<Long> getAdminStringToList() {
        if (TextUtils.isEmpty(groupAdmin)) {
            return null;
        }
        List<Long> idList = new ArrayList<Long>();

        if (!TextUtils.isEmpty(groupAdmin) && groupAdmin.length() > 2) {

            try {
                JSONArray data = new JSONArray(groupAdmin);

                for (int i = 0; i < data.length(); i++) {
                    JSONObject obj = data.getJSONObject(i);
                    if (obj == null) {
                        continue;
                    }
                    long id = obj.optLong("uid", ContactUtil.INVALID_ID);
                    if (id != ContactUtil.INVALID_ID) {
                        idList.add(id);
                    }
                }

            } catch (Exception e) {
                VLog.d("GroupModel", "exception");
            }

        }
        return idList;
    }

    /**
     * 单个添加groupadmin
     *
     * @param uid
     */
    public void addGroupAdmin(long uid) {
        List<Long> groupAdminList = getAdminStringToList();
        if (groupAdminList == null) {
            groupAdminList = new ArrayList<Long>();
        }
        if (!groupAdminList.contains(uid)) {
            groupAdminList.add(uid);
            groupAdmin = getAdminToString(groupAdminList);
        }
    }


//	public String getListToString(List<UserModel> users){
//
//		JSONArray json = new JSONArray();
//		try {
//			for (UserModel userModel : users) {
//				if (userModel.getUserId() == CocoConstants.INVALID_ID)
//					continue;
//				JSONObject o = new JSONObject();
//				o.put("uid", userModel.getUserId());
//				json.put(o);
//			}
//		} catch (Exception e) {
//			VLog.d("GroupModel", "exception");
//		}
//		return json.toString();
//	}

    public void addUsers(List<Long> uids) {
        Set<Long> users = getUserIdSet();
        for (int i = 0; i < uids.size(); i++) {
            long uid = uids.get(i);
            if (users.contains(uid)) {
                continue;
            }
            users.add(uid);
        }
        String userString = getSetToString(users);
        groupMembers = userString;
        if (users.isEmpty()) {
            VLog.e("TAG_CONTACT", "try to setGroupMembers with empty:" + Log.getStackTraceString(new Throwable()));
        }
        UserFTSHelper.addGroupMembers(this, uids);
    }

    /**
     * 删除群成员
     *
     * @param uid
     */
    public void removeUser(long uid) {
        Set<Long> users = getUserIdSet();
        users.remove(uid);
        String userString = getSetToString(users);
        groupMembers = userString;
        if (users.isEmpty()) {
            VLog.e("TAG_CONTACT", "try to setGroupMembers with empty:" + Log.getStackTraceString(new Throwable()));
        }
        UserFTSHelper.removeGroupMembers(this, Collections.singletonList(uid));
    }

    /**
     * 删除管理员
     *
     * @param uid
     */
    public void removeManager(long uid) {
        List<Long> users = getAdminStringToList();
        if (users != null) {
            users.remove(uid);
            groupAdmin = getAdminToString(users);
            if (users.isEmpty()) {
                VLog.e("TAG_CONTACT", "try to setGroupMembers with empty1:" + Log.getStackTraceString(new Throwable()));
            }
        }
    }


    /**
     * 获取所有userid
     *
     * @return
     */
    public Set<Long> getUserIdSet() {

        Set<Long> idList = new LinkedHashSet<Long>();

        if (!TextUtils.isEmpty(groupMembers) && groupMembers.length() > 2) {

            try {
                JSONArray data = new JSONArray(groupMembers);

                for (int i = 0; i < data.length(); i++) {
                    JSONObject obj = data.getJSONObject(i);
                    if (obj == null) {
                        continue;
                    }
                    long id = obj.optLong("uid", ContactUtil.INVALID_ID);
                    if (id != ContactUtil.INVALID_ID) {
                        idList.add(id);
                    }
                }

            } catch (Exception e) {
                VLog.e("TAG_CONTACT", " parse group members json fail %d", id);
            }

        }
        return idList;
    }

    public String getQrCodrUrl() {
        return qrCodrUrl;
    }

    public void setQrCodrUrl(String qrCodrUrl) {
        this.qrCodrUrl = qrCodrUrl;
    }

    public String getBackground() {
        return background;
    }

    public void setBackground(String background) {
        this.background = background;
    }

    public long getGroupUpdateTime() {
        return groupUpdateTime;
    }

    public void setGroupUpdateTime(long groupUpdateTime) {
        this.groupUpdateTime = groupUpdateTime;
    }

    public String getGroupAdmin() {
        return groupAdmin;
    }

    public void setGroupAdmin(String groupAdmin) {
        this.groupAdmin = groupAdmin;
    }

    public boolean isVoipGroup() {
        return (groupType == VOIP_GROUP);
    }

    public String getShareLink() {
        return shareLink;
    }

    public void setShareLink(String shareLink) {
        this.shareLink = shareLink;
    }

    public long getLinkExpireTime() {
        return linkExpireTime;
    }

    public void setLinkExpireTime(long linkExpireTime) {
        this.linkExpireTime = linkExpireTime;
    }

    public long getCreateTime() {
        return createTime;
    }

    public void setCreateTime(long createTime) {
        this.createTime = createTime;
    }

    public void setLastRequestTime(long lastRequestTime) {
        this.lastRequestTime = lastRequestTime;
    }

    public long getLastRequestTime() {
        return lastRequestTime;
    }


    public void setNeedRequestInfo(boolean needRequestInfo) {
        this.needRequestInfo = needRequestInfo;
    }

    public boolean isNeedRequestInfo() {
        return needRequestInfo;
    }

    @Override
    public String toString() {
        return "GroupModel{" +
                "id=" + id +
                ", groupName='" + groupName + '\'' +
                ", groupAvatar='" + groupAvatar + '\'' +
                ", groupMembers='" + groupMembers + '\'' +
                ", isSilent=" + isSilent +
                ", creator=" + creator +
                ", discription='" + discription + '\'' +
                ", memberCount=" + memberCount +
                ", background='" + background + '\'' +
                ", qrCodrUrl='" + qrCodrUrl + '\'' +
                ", groupUpdateTime=" + groupUpdateTime +
                ", groupAdmin='" + groupAdmin + '\'' +
                ", vopids='" + vopids + '\'' +
                ", groupType=" + groupType +
                ", displayName='" + displayName + '\'' +
                ", groupCallName='" + groupCallName + '\'' +
                ", originalAvatar='" + originalAvatar + '\'' +
                ", cacheUIds=" + cacheUIds +
                ", shareLink=" + shareLink +
                ", linkExpireTime=" + linkExpireTime +
                '}';
    }
}
